//
//  BConnector.m
//  car
//
//  Created by chenxu on 15/3/23.
//  Copyright (c) 2015年 chenxu. All rights reserved.
//

#import "BConnector.h"
#import "BPush.h"



static platform plat;

//#define aapikey @"5aYLlM2xYOF5ay8tHq95dgDc"
//#define sk  @"giv8YBC09FsI5rGeO3cy3HY5PUh0rqdt"
@implementation BConnector


/*!
 *  @brief  广播
 *  @return
 */
+ (NSDictionary*)push_msg_to_all_Params:(PrivateMessage*)msg order:(Order*)order{
    
    return @{@"apikey" : kAPIkey_ios,
             @"messages" :[[self msg:msg order:order]JSONString] ,
             @"method" : @"push_msg",
             @"msg_keys" : @"msgkey",
             @"push_type" : @"3",               //广播
             @"timestamp" :  [self getTimeString],
             };
}


+ (void)setPlatform:(platform)platform{
    plat = platform;
}

/*!
 *  @brief  单播,需要知道对方userid 和 channel id
 *  @return
 */
+ (NSDictionary*)push_msg_to_single_Params:(PrivateMessage*)msg order:(Order*)order{
    //发给安卓
    NSDictionary* ret ;
    switch (plat) {
        case android:
            ret = @{@"apikey" : kAPIkey_android,
                   @"messages" :[[self msg:msg order:order]JSONString] ,
                   @"device_type" : @"3",       //3安卓，4ios
                   @"method" : @"push_msg",
                   @"msg_keys" : @"channel_msg_key",
                   @"user_id" : order.userid,
                   @"channel_id" : order.channelid,
                   @"push_type" : @"1",         //单播
                   @"timestamp" :  [self getTimeString],
                   };
            break;
            
        case ios:
            ret = @{@"apikey" : kAPIkey_ios,
                   @"messages" :[[self msg:msg order:order]JSONString] ,
                   @"device_type" : @"4",
                   @"method" : @"push_msg",
                   @"msg_keys" : @"channel_msg_key",
                   @"user_id" : order.userid,
                   @"channel_id" : order.channelid,
                   @"push_type" : @"1",         //单播
                   @"timestamp" :  [self getTimeString],
                 //  @"deploy_status" : @"1"      //1.生成状态 2.开发状态
                                                //文档上1.开发状态 2.生成状态
                   };
            break;
    }
    
    //发给ios
    return ret ;
}


/*!
 *  @brief  获取当前设备绑定情况
 *  @return
 */
+ (NSDictionary*)query_bindlist_Params{
    return @{@"method" : @"query_bindlist",
             @"apikey" : kAPIkey_ios,
             @"user_id" : [BPush getUserId],
             @"timestamp" : [self getTimeString],
             };
}

/*!
 *  @brief  查看当前ios的apn证书
 *  @return
 */
+ (NSDictionary*)query_app_ioscert_Params{
    return @{@"method" : @"query_app_ioscert",
             @"apikey" : kAPIkey_ios,
             @"timestamp" : [self getTimeString],
             };
}

/*!
 *  @brief  获取某个人的å离线消息
 *  @return
 */
+ (NSDictionary*)fetch_Params{
    
        return      @{
                      @"method" : @"fetch_msg",
                      @"apikey" : kAPIkey_ios,
                      @"user_id" : [BPush getUserId],
                      @"timestamp" : [self getTimeString]
                     };


}


/*!
 *  @brief  获取当前unix时间戳
 *  @return 时间string
 */
+ (NSString *)getTimeString{
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];  //  *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a]; //转为字符型
    
    // NSLog(@"%ld", time(NULL));
    return timeString;
}

/*!
 *  @brief  创建消息参数字典
 *  @param str 要发送的消息
 *  @return 参数字典
 */
+ (NSDictionary*)msg:(PrivateMessage*)primsg order:(Order*)order
{
    //空格需要编码，因为空格无法通过签名算法
    NSString* talk = [primsg.Talk stringByReplacingOccurrencesOfString:@" " withString:@"&n"];
    NSDictionary * ret;
    switch (plat) {
        case android:
            ret = @{
                    @"Talk"  :  talk,
                    @"Orderid"   : order.Orderid,
                    };
            break;
            
        case ios:
            ret = @{
                    @"aps"   :   @{
                            @"alert": talk,
                            @"sound": @"ttt",
                            @"badge": @"0",
                            @"content-available"  :   @"yes",
                            },
                    @"orderid"   : order.Orderid,
                    };
            break;
    }
    return ret;
}

/*!
 *  @brief  路径，只用在push_msg这个方法中
 *  @return 路径
 */
+ (NSString *)toPath{
    return @"rest/2.0/channel/channel";
}

/*!
 *  @brief  默认路径，用在大多数情况
 *  @return 路径
 */
+ (NSString* )toPathWithChannelid{
    return [[NSString alloc]initWithFormat:@"rest/2.0/channel/%@",[BPush getChannelId]];
}

/*!
 *  @brief  计算参数字典的sign
 *  @param dict 传入字典
 *  @return sign字符串
 */
+ (NSString *)getSign:(NSDictionary* )dict withChannelIdPath:(BOOL)withchannel{
    
    NSArray *keys = [dict allKeys];
    
    //给键名排序
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    
    //1.http_method
    NSString * baseString = @"POST";
    
    //2.base url
    baseString = [baseString stringByAppendingString:kBaiduPath_Base];
    
    //3.url path
    if (withchannel) {
        baseString = [baseString stringByAppendingString:[self toPathWithChannelid]];//只有这个方法是普通路径
    }
    else{
        baseString = [baseString stringByAppendingString:[self toPath]];
    }
    
    //4.key=value...
    for (NSString *categoryId in sortedArray) {
        baseString = [baseString stringByAppendingFormat:@"%@=%@",categoryId,[dict objectForKey:categoryId]];
       // NSLog(@"[dict objectForKey:categoryId] === %@",[dict objectForKey:categoryId]);
    }
    
    //5.secret key
    switch (plat) {
        case ios:
            baseString = [baseString stringByAppendingString:kSecretkey_ios];
            break;
        case android:
            baseString = [baseString stringByAppendingString:kSecretkey_android];
            break;
    }


    //6.urlencode
    NSString* encodedString = [baseString URLEncodedString];
    
    
    NSLog(@"\n%@",baseString);
    NSLog(@"\n%@",encodedString);

    //7.md5
    NSString* sign = [encodedString md5Str];    
    return sign;
}

/*!
 *  @brief  添加sign键值对
 *  @param params 被加的字典
 *  @return 新字典
 */
+ (NSDictionary* )addsign:(NSDictionary*)params withChannelIdPath:(BOOL)withchannel{
    NSMutableDictionary* temp = [[NSMutableDictionary alloc]initWithDictionary:params];
    [temp setValue:[self getSign:params withChannelIdPath:withchannel] forKey:@"sign"];
    return temp;
}



/*!
 *  @brief  获取各种参数字典
 *  @param method 方法
 *  @return 
 */
+ (NSDictionary* )toParams:(method)method{
    NSDictionary* ret = nil;
    switch (method) {
        case query_bindlist:
            ret = [self query_bindlist_Params];
            ret = [self addsign:ret withChannelIdPath:false];
            break;
            
        case fetch_msgs_all:
            ret = [self fetch_Params];
            ret = [self addsign:ret withChannelIdPath:false];
            break;
            
        case fetch_msgs_single:
            ret = [self fetch_Params];
            ret = [self addsign:ret withChannelIdPath:true];
            break;
            
        case query_app_ioscert:
            ret = [self query_app_ioscert_Params];
            ret = [self addsign:ret withChannelIdPath:true];
            break;
            
        default:
            break;
    }
    return ret;
}

+ (NSDictionary* )toMsgParams:(pushmethod)method msg:(PrivateMessage*)msg  order:(Order*)order{
    NSDictionary* ret = nil;
    switch (method) {
        case push_msg_to_all:
            ret = [self push_msg_to_all_Params:msg order:(Order*)order];
            ret = [self addsign:ret withChannelIdPath:false];
            
            break;
            
        case push_msg_to_single:
            ret = [self push_msg_to_single_Params:msg order:(Order*)order];
            ret = [self addsign:ret withChannelIdPath:false];
            break;
            
        default:
            break;
    }
    return ret;
}

@end
